<?php
require_once 'base.php';

$tpl = new Template('t');
$tpl->setFile ( "main", "main.html" );
$tpl->setFile ( "viewblog", "viewblog.html" );
$tpl->setBlock ( "viewblog", "comment_block", "comment_blocks" );

$db = conn();

// ------------- 页面基本信息 -------------
// 分类
$category_str = '';
foreach ($CFG['category'] as $key => $category){
	$category_str .= "<li class=\"cat-item\"><a href=\"index.php?search=category&category={$key}\" title=\"查看所有分类为 {$category} 的文章\">{$category}</a></li>";
}
// 标签
$sql_tags = "SELECT * FROM tags ORDER BY amount DESC LIMIT 25";
$rs=$db->query($sql_tags, MYSQL_ASSOC);
$tag_str = '';
foreach($rs as $tag){
    $tag['name'] = stripslashes($tag['name']);
	$tag_str .= "<a href=\"index.php?search=tag&tag={$tag['name']}\" title=\"查看所有标记为 {$tag['name']} 的文章\">{$tag['name']}</a> ";
}
// 显示
$tpl->setVar(array(
    'website_url' => $CFG['website']['url'],
    'web_title' => $CFG['website']['page_title'],
	'description' => $CFG['website']['description'],
	'category_str' => $category_str,
	'tag_str' => $tag_str
));
// ------------- end 页面基本信息 -------------

// ------------- 添加评论 -------------
if (pm() == "POST"){
	$aid = del_space(fpost('id', 0));
	if ($aid){
		$nickname = addslashes(trim(fpost('author')));
		$mail = addslashes(trim(fpost('email')));
		$website = addslashes(trim(fpost('url')));
		$contents = addslashes(trim(fpost('comment')));
        $submit_ip = ip2long(getip());
        $submit_ip = $submit_ip ? $submit_ip : 0;
		$submit_time = time();

		// 检查时间
		$allow_comment = 1;
		$sql_check_time = "SELECT * FROM comment WHERE aid='{$aid}' AND submit_ip={$submit_ip} AND status=0 ORDER BY id DESC LIMIT 1";
		$rs_check_time=$db->query($sql_check_time, MYSQL_ASSOC);
		if (!empty($rs_check_time)){
			if (($submit_time - $rs_check_time[0]['submit_time']) < 10*60){ // 十分钟内允许评论一条
				$allow_comment = 0;
			}
		}
		if (!$allow_comment){
			$tpl->setVar("add_comment_alert", "alert(\"你慢点发，太快了我怕吃不消!如果这是你第一次评论这文章，那就是我生病了，麻烦你告诉我家主人，谢谢。E-mail:guoyu1268@qq.com\")");
		}else{
			// 验证数据合法性
			if ($nickname == ''){
				die("昵称不能为空，请<a href=\"javascripe: history.back();\">返回</a>重试！");
			}else if (strlen_utf8($nickname) > 20){
				die("昵称最多不得超过20个字符，请<a href=\"javascripe: history.back();\">返回</a>重试！");
			}
			if ($mail == ''){
				die("邮箱不能为空，请<a href=\"javascripe: history.back();\">返回</a>重试！");
			}else if(strlen_utf8($mail) > 50){
				die("邮箱最多不得超过50个字符，请<a href=\"javascripe: history.back();\">返回</a>重试！");
			}else if (!check_mail($mail)){
				die("邮箱格式不正确，请<a href=\"javascripe: history.back();\">返回</a>重试！");
			}
			if ($website != ''){
				if (strlen_utf8($website) > 100){
					die("个人主页最多不得超过100个字符，请<a href=\"javascripe: history.back();\">返回</a>重试！");
				}else if (!check_url($website)){
					die("个人主页格式不正确，请<a href=\"javascripe: history.back();\">返回</a>重试！");
				}
			}
			if ($contents == ''){
				die("内容不能为空，请<a href=\"javascripe: history.back();\">返回</a>重试！");
			}else if (strlen_utf8($contents) > 500){
				die("内容最多不得超过500个字符，请<a href=\"javascripe: history.back();\">返回</a>重试！");
			}

			$sql_insert = "INSERT INTO comment (aid, nickname, mail, website, contents, submit_time, submit_ip) VALUES('{$aid}', '{$nickname}', '{$mail}', '{$website}', '{$contents}', {$submit_time}, {$submit_ip})";
			if ($db->query($sql_insert)){
				// 更新评论数
				$sql_update = "UPDATE article SET comment=comment+1 WHERE aid='{$aid}'";
				$db->query($sql_update);

				//添加成功
                header("Location: viewblog.php?id={$aid}#{$submit_time}");
			}else{
				//添加失败提示
			}
		}
	}
}

// ------------- 显示文章内容 -------------
$id = fget("id", 0);
if ($id){
	$sql = "SELECT * FROM article WHERE aid='{$id}' AND status>-1";
	$rs=$db->query($sql, MYSQL_ASSOC);

	if(!empty($rs)){
		// 更新浏览次数
		$sql_update = "UPDATE article SET amount=amount+1, last_view_time=" . time() . " WHERE aid='{$id}'";
		$db->query($sql_update);

		$v = $rs[0];

        $tpl->setVar('page_title', stripslashes($v['title']) . " - " . $CFG['website']['page_title']); // 页面title

		// 标签文字加链接
		if (!empty($v['tags'])){
            $v['tags'] = stripslashes($v['tags']);
			$tag_arr = explode(",", $v['tags']);
			$tags_str = "";
			foreach ($tag_arr as $tag){
				$tags_str .= "<a href=\"index.php?search=tag&tag={$tag}\">{$tag}</a> , ";
			}
			$tags_str = substr($tags_str, 0, -3);
		}else{
			$tags_str = "没有标签";
		}
		// 分类文字加链接
		$category_str = "<a href=\"index.php?search=category&category={$v['category']}\">{$CFG['category'][$v['category']]}</a>";

		$tpl->setVar(array(
			"aid" => $v['aid'],
			"title" => stripslashes($v['title']),
			"contents" => stripslashes($v['contents']),
			"category" => $category_str,
			"tags" => stripslashes($tags_str),
			"month" => date("n", $v['submit_time']),
			"date" => date("d", $v['submit_time']),
			"submit_time" => date("h:i A", $v['submit_time']),
			"amount" => $v['amount'],
			"comment" => $v['comment'] //评论数
		));

		// 列出评论内容
		$sql_comment = "SELECT * FROM comment WHERE aid='{$id}' AND status>-1";
		$rs=$db->query($sql_comment, MYSQL_ASSOC);
		if (!empty($rs)){
			foreach($rs as $v){
				$tpl->setVar(array(
					"nickname" => stripslashes($v['nickname']),
					"website" => empty($v['website']) ? "href=\"javascript: void(0);\"" : "href=\"" . stripslashes($v['website']) . "\" target=\"_blank\"",
					"comment_contents" => nl2br(strip_tags(stripslashes($v['contents']))),
					"comment_time" => date("Y年m月d日 h:i A", $v['submit_time']),
                    "comment_mark" => $v['submit_time']
				));
				$tpl->parse ("comment_blocks", "comment_block", true);
			}
		}else{
			//评论读取失败，待处理
		}
	}else{
		die("你来晚了，文章已经没有了！<a href=\"javascript:void(0);\" onclick=\"javascript:history.back();\">返回</a>");
        $tpl->setVar('page_title', "你来晚了，文章已经没有了！_" . $CFG['website']['page_title']); // 页面title
	}
}else{
	die("地址参数错误！<a href=\"javascript:void(0);\" onclick=\"javascript:history.back();\">返回</a>");
    $tpl->setVar('page_title', "地址参数错误！_" . $CFG['website']['page_title']); // 页面title
}

$db->close();

$tpl->parse('main_content', 'viewblog');
$tpl->p("main");
?>